package com.kingtown.inventory;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.json.JSONObject;
import com.rscja.deviceapi.RFIDWithUHFUART;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.net.NetworkInterface;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;


public class Utils {
    private static ProgressDialog progressDialog;

    private static int progress;
    private static ProgressBar mProgress;
    static AlertDialog.Builder builder;

    public static void showProgressDialog(Context context, String title, String message) {
        if (progressDialog == null) {
            Log.i("showProgressDialog","is null");
            progressDialog = ProgressDialog.show(context, title,
                    message, true, false);
        } else if (progressDialog.isShowing()) {
            Log.i("showProgressDialog","is not null and showing");
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }else{
            Log.i("showProgressDialog","is not null and is not show");
            progressDialog = ProgressDialog.show(context, title,
                    message, true, false);
        }
        progressDialog.show();
    }

    public static void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
//            progressDialog.hide();
        }
    }

    static int yourChoice;


    public static String toHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }

    public static String fillHexZero(String code) {
        if (code.length() % 4 > 0) {
            return fillHexZero(Utils.toHexString("0") + code);
        } else {
            return code.toUpperCase();
        }
    }

    public static String fillZero(String code) {
        if (code.length() % 4 > 0) {
            return fillZero("0" + code);
        } else {
            return code.toUpperCase();
        }
    }



    public static String convertTime(long time, String patter) {
        SimpleDateFormat sdf = new SimpleDateFormat(patter);
        return sdf.format(new Date(time));
    }

    public static String getTrueEpcByBarCode(String barCode,String globalBatchCode) {
        String fullCode = barCode + "," + globalBatchCode;
        String tempEpc = Utils.toHexString(fullCode);
        while (tempEpc.length() < 96) {
            tempEpc += "F";
        }
        return tempEpc;
    }

    public static String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("device.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

    public static String getMacFromHardware() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private static final String ENCODE_KEY = "weixinkeji202311";
    private static final String IV_KEY = "0000000000000000";


    public static String encryptFromString(String data, Mode mode, Padding padding) {
        AES aes;
        if (Mode.CBC == mode) {
            aes = new AES(mode, padding,
                    new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
                    new IvParameterSpec(IV_KEY.getBytes()));
        } else {
            aes = new AES(mode, padding,
                    new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
        }
        return aes.encryptBase64(data, StandardCharsets.UTF_8);
    }

    public static String decryptFromString(String data, Mode mode, Padding padding) {
        AES aes;
        if (Mode.CBC == mode) {
            aes = new AES(mode, padding,
                    new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
                    new IvParameterSpec(IV_KEY.getBytes()));
        } else {
            aes = new AES(mode, padding,
                    new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
        }
        try {
            byte[] decryptDataBase64 = aes.decrypt(data);
            return new String(decryptDataBase64, StandardCharsets.UTF_8);
        } catch (Exception exception) {
            return null;
        }
    }

    public static String checkLicense(String serial,String filePath) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = null;
        String password = null;

        try {
            FileReader fileReader = new FileReader(filePath);
            String json = fileReader.readString();
            password = json;
        } catch (Exception e) {
            Log.e("checkLicense", "无法读取文件");
            return "0x01";
        }
        String keySerial = decryptFromString(password, Mode.ECB, Padding.PKCS5Padding);
        if (StrUtil.isBlank(keySerial)) {
            Log.e("checkLicense", "无法解析license");
            return "0x02";
        }
        Log.i("keySerial", keySerial);
        String[] key = keySerial.split(",");
        if (key.length > 1) {
            try {
                Date keyDate = sdf.parse(key[1]);
                Date now = new Date();
                if (keyDate.compareTo(now) < 0) {
                    Log.e("checkLicense", "时间已过期");
                    return "0x03";
                }
            } catch (ParseException e) {
                Log.e("checkLicense", "日期解析失败");
                return "0x04";
            }
        }
        if (!key[0].equals(serial)) {
            Log.e("checkLicense", "序列号不匹配");
            return "0x05";
        }
        return "0x00";
    }

    public static boolean setPower(MainApplication mainApplication, Context context,RFIDWithUHFUART reader,String power){
        if(mainApplication.loopFlag){
            reader.stopInventory();
        }
        int curPower = reader.getPower();
        if(curPower == Integer.parseInt(power)){
            Log.i("set power","ok");
            return true;
        }
        boolean result = reader.setPower(Integer.parseInt(power));
        if (!result) {
            Toast.makeText(context, "功率设置失败", Toast.LENGTH_SHORT).show();
        }
        return result;
    }

    public static void showSingleChoiceDialog(Context context, RFIDWithUHFUART reader,boolean isLoop) {
        final String[] items = {"5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"};
        yourChoice = -1;
        AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(context);
        int currentPower = reader.getPower();
        singleChoiceDialog.setTitle("选择功率");
        singleChoiceDialog.setSingleChoiceItems(items, currentPower - 5, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                yourChoice = which;
            }
        });
        singleChoiceDialog.setPositiveButton("确定", (dialog, which) -> {
            if (yourChoice != -1) {
                if(isLoop){
                    reader.stopInventory();
                }
                boolean result = reader.setPower(Integer.parseInt(items[yourChoice]));
                if (result) {
                    Toast.makeText(context, "功率设置成功，如需盘点请再次开启", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "功率设置失败，如需盘点请再次开启", Toast.LENGTH_SHORT).show();
                }
            }
        });
        singleChoiceDialog.show();
    }

//    public static void main(String[] args) {
//        int i = 314;
//        int j = 314/100;
//        System.out.println(j+"");
//    }
}
